$(function () {
    var $unitSelect = $("#unitSelect"),
        $sectorSelect = $("#sectorSelect"),
        $departmentSelect = $("#departmentSelect"),
        $nameIpt = $("#nameIpt");
    var ERR_NULL = "请根据所需的条件进行查询。";
    
    // 初始化
    unitChange($unitSelect);
    sectorChange($sectorSelect);
	
    // 让主体内容最小高度刚好撑满整个可视窗口
    var winH = $(window).height();

    $("#mainBody").css("min-height", winH - 272 + "px");

    // 让IE浏览器支持文本输入框的placeholder属性
    $("input[type='text']").placeholder();

    var $resultArea = $("#resultArea");

    // 排序
    $("#rank").find(".js-radio").click(function () {
        var $this = $(this);
        var radioValue = $this.val(),
        	unitValue = $unitSelect.val(),
        	sectorValue = $sectorSelect.val(),
        	departmentValue = $departmentSelect.val(),
        	nameValue = $.trim($nameIpt.val());

        $this.next(".rank__item__circle").find(".circle").addClass("active")
            .end().closest(".rank__item").siblings().find(".circle").removeClass("active");
        
        if($(".text-prompt").html() == ERR_NULL){
        	return false;
        }
        else{
        	$.ajax({
            	url: "getList",
                type: "post",
                dataType: "json",
                data: {
                	groupId: unitValue,
                	depId: sectorValue,
                	officeId: departmentValue,
                    name: nameValue,
                    nameOrderNo: radioValue
                },
                beforeSend:function(XHR) {
                    $("#loading").show();
                },
    			complete:function(XHR, TS) {
                    $("#loading").hide();
                },
                success: function (data) {
                	var flag = data.returnFlag,
                    	list = data.list;

                    if (flag == 0) {
                        if (list.length === 0) {
                        	$(".result-area").find(".text-prompt").html("没有满足条件的记录！").show().end().find(".result").hide().find("#resultArea").empty();
                        }
                        else {
                            // 动态添加DOM
                            var htmlList = "",
                                // textarea中的模板HTML
                                htmlTemp = $("textarea").val();

                            list.forEach(function (object) {
                                htmlList += htmlTemp.temp(object);
                            });
                            $(".result-area").find(".text-prompt").empty().hide().end().find(".result").show().find("#resultArea").html(htmlList);
                        }
                    }
                },
                error: function (errorThrown) {
                    alert("请求数据失败！");
                }
            });
        }
    });
    
    // 下拉框动态改变
    // 单位下拉框
    $unitSelect.change(function () {
    	var $this = $(this);
    	
    	unitChange($this);
    });
    
    function unitChange(that){
    	var unitValue = that.val() || 2;

        if (unitValue != "") {
            $.ajax({
                url: "showDep",
                type: "get",
                dataType: "json",
                data: {
                	groupId: unitValue
                },
                beforeSend:function(XHR) {
                    $("#loading").show();
                },
    			complete:function(XHR, TS) {
                    $("#loading").hide();
                },
                success: function (data) {
                    var flag = data.returnFlag,
                        list = data.list;
                    
                    if (flag == 0) {
                        if (list.length !== 0) {
                            $sectorSelect.html("");// 清空下拉框里的值
                            $("<option value='-1'>全部</option>").appendTo($sectorSelect);
                            for (var i = 0; i < list.length; i++) {
                                $("<option value='" + list[i].id + "'>" + list[i].name + "</option>").appendTo($sectorSelect);
                            }
                        }
                    }
                },
                error: function (errorThrown) {
                    alert("请求数据失败！");
                }
            });
        }
    }

    // 部门下拉框
    $sectorSelect.change(function () {
    	var $this = $(this);
    	
    	sectorChange($this);
    });
    
    function sectorChange(that) {
    	var sectorValue = that.val() || 113;

        if (sectorValue != "") {
            $.ajax({
                url: "showOffice",
                type: "get",
                dataType: "json",
                data: {
                	depId: sectorValue
                },
                beforeSend:function(XHR) {
                    $("#loading").show();
                },
    			complete:function(XHR, TS) {
                    $("#loading").hide();
                },
                success: function (data) {
                	var flag = data.returnFlag,
                    	list = data.list;

                    if (flag == 0) {
                        if (list.length !== 0) {
                            $departmentSelect.html("");
                            $("<option value='-1'>全部</option>").appendTo($departmentSelect);
                            for (var i = 0; i < list.length; i++) {
                                $("<option value='" + list[i].id + "'>" + list[i].name + "</option>").appendTo($departmentSelect);
                            }
                        }
                    }
                },
                error: function (errorThrown) {
                    alert("请求数据失败！");
                }
            });
        }
    }

    // 查询结果
    $("#searchBtn").click(function () {
        var unitValue = $unitSelect.val(),
            sectorValue = $sectorSelect.val(),
            departmentValue = $departmentSelect.val(),
            nameValue = $.trim($nameIpt.val());

        $.ajax({
            url: "getList",
            type: "post",
            dataType: "json",
            data: {
            	groupId: unitValue,
            	depId: sectorValue,
            	officeId: departmentValue,
                name: nameValue,
                nameOrderNo: 1
            },
            beforeSend:function(XHR) {
                $("#loading").show();
            },
			complete:function(XHR, TS) {
                $("#loading").hide();
            },
            success: function (data) {
            	var flag = data.returnFlag,
                	list = data.list;

                if (flag == 0) {
                    if (list.length === 0) {
                    	$(".result-area").find(".text-prompt").html("没有满足条件的记录！").show().end().find(".result").hide().find("#resultArea").empty();
                    }
                    else {
                        var htmlList = "",
                            htmlTemp = $("textarea").val();

                        list.forEach(function (object) {
                            htmlList += htmlTemp.temp(object);
                        });
                        $(".result-area").find(".text-prompt").empty().hide().end().find(".result").show().find("#resultArea").html(htmlList);
                    }
                }
            },
            error: function (errorThrown) {
                alert("请求数据失败！");
            }
        });
    });
    
    $("#nameIpt").keypress(function(event){
    	if(event.keyCode == 13){
    		event.preventDefault();
    		$("#searchBtn").click();
    	}
    });
    
    // 让IE8支持forEach语法
	 if (!Array.prototype.forEach) {
	
	   Array.prototype.forEach = function(callback/*, thisArg*/) {
	
	     var T, k;
	
	     if (this == null) {
	       throw new TypeError('this is null or not defined');
	     }
	
	     // 1. Let O be the result of calling toObject() passing the
	     // |this| value as the argument.
	     var O = Object(this);
	
	     // 2. Let lenValue be the result of calling the Get() internal
	     // method of O with the argument "length".
	     // 3. Let len be toUint32(lenValue).
	     var len = O.length >>> 0;
	
	     // 4. If isCallable(callback) is false, throw a TypeError exception. 
	     // See: http://es5.github.com/#x9.11
	     if (typeof callback !== 'function') {
	       throw new TypeError(callback + ' is not a function');
	     }
	
	     // 5. If thisArg was supplied, let T be thisArg; else let
	     // T be undefined.
	     if (arguments.length > 1) {
	       T = arguments[1];
	     }
	
	     // 6. Let k be 0.
	     k = 0;
	
	     // 7. Repeat while k < len.
	     while (k < len) {
	
	       var kValue;
	
	       // a. Let Pk be ToString(k).
	       //    This is implicit for LHS operands of the in operator.
	       // b. Let kPresent be the result of calling the HasProperty
	       //    internal method of O with argument Pk.
	       //    This step can be combined with c.
	       // c. If kPresent is true, then
	       if (k in O) {
	
	         // i. Let kValue be the result of calling the Get internal
	         // method of O with argument Pk.
	         kValue = O[k];
	
	         // ii. Call the Call internal method of callback with T as
	         // the this value and argument list containing kValue, k, and O.
	         callback.call(T, kValue, k, O);
	       }
	       // d. Increase k by 1.
	       k++;
	     }
	     // 8. return undefined.
	   };
	 }

    // 一个固定的基于字符串原型的扩展方法
    String.prototype.temp = function (obj) {
        return this.replace(/\$\w+\$/gi, function (matchs) {
            var returns = obj[matchs.replace(/\$/g, "")];

            return (returns + "") == "undefined" ? "" : returns;
        });
    };
});